//
//  EarningsDetailViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/13.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "EarningsDetailViewController.h"
#import "EarningsDetailView.h"
#import "EarnDetailTableViewCell.h"
#import <Masonry.h>
//点击筛选弹出框View
#import "SelectView.h"
#import "WithdrawViewController.h"

#import "EarningsDetailModelPack.h"
#import "GetAllProfitModelPack.h"

#import <MJRefresh.h>

@interface EarningsDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)EarningsDetailView *ev;
@property(nonatomic,strong)SelectView *sv;

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *modelArray;


/**
 账户明细查询类型 0 分润  1 提现   2 全部
 */
@property(nonatomic,strong)NSString *typeStr;

// 上拉下拉刷新相关属性
@property(nonatomic,assign) NSInteger curPageNum;
@property(nonatomic,strong) NSString *ifHasMore; // 是否有更多数据 0:无 1:有
@property(nonatomic,assign) ETRefreshType refreshType;
@property(nonatomic,assign) BOOL isLoading;

//可提现金额
@property(nonatomic,strong)NSString *ableWithdrawNumLabStr;

@end

@implementation EarningsDetailViewController

-(NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([self.ableWithdrawNumLabStr floatValue] > 0) {
        self.ev.withdrawBtn.userInteractionEnabled = YES;
        self.ev.withdrawBtn.backgroundColor = ETColorWithRGB(91, 113, 255);
    }else
    {
        self.ev.withdrawBtn.userInteractionEnabled = NO;
        self.ev.withdrawBtn.backgroundColor = ETColorWithRGB(219, 224, 255);
    }
    
    
}
-(void)dealEarningsDetailResponse:(id)responseObject
{
    EarningsDetailResponse *earningsDetailResponse = [EarningsDetailResponse mj_objectWithKeyValues:responseObject];
    NSLog(@"%@",earningsDetailResponse.response.totalIncome);
    self.ev.totalEarnValueLab.text = [NSString stringWithFormat:@"%@%@",@"￥",earningsDetailResponse.response.totalIncome];
    self.ev.ableWithdrawNumLab.text = [NSString stringWithFormat:@"%@%@",@"账户可提现余额: ￥",earningsDetailResponse.response.balance];
    self.ableWithdrawNumLabStr = earningsDetailResponse.response.balance;
    
    if ([earningsDetailResponse.response.balance floatValue] > 0) {
        self.ev.withdrawBtn.userInteractionEnabled = YES;
        self.ev.withdrawBtn.backgroundColor = ETColorWithRGB(91, 113, 255);
    }else
    {
        self.ev.withdrawBtn.userInteractionEnabled = NO;
        self.ev.withdrawBtn.backgroundColor = ETColorWithRGB(219, 224, 255);
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //无网络占位
    
    self.title = @"收益详情";
    self.view.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:244 / 255.0 blue:246 / 255.0 alpha:1];
    
    //创建topView
    [self createTopView];
    //创建TableView
    [self createTableView];
    // 上拉下拉刷新相关设置
    self.curPageNum = 1;
    self.ifHasMore = @"1";
    [self createFooterView];
    [self createHeaderView];
    
    
    //点击筛选按钮
    [self.ev.selectbtn addTarget:self action:@selector(selectbtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    self.ev.selectImv.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectbtnAction)];
    [self.ev.selectImv addGestureRecognizer:tap];
    
    [self.ev.withdrawBtn addTarget:self action:@selector(clickwithdrawBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //获取总收益和账户可提现余额
    [self GetAmount];
    //查询所有分润和佣金
    //默认查询全部
    self.typeStr = @"2";
    [self getAllshareProfit];
}

#pragma mark 上拉刷新&下拉刷新
- (void)createHeaderView{
    MJRefreshNormalHeader *headerView = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 设置文字
    [headerView setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [headerView setTitle:@"释放刷新" forState:MJRefreshStatePulling];
    [headerView setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    // 设置字体
    headerView.stateLabel.font = [UIFont systemFontOfSize:15];
    headerView.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    // 设置颜色
    headerView.stateLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1];
    headerView.lastUpdatedTimeLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1];
    //隐藏上次刷新时间
    headerView.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = headerView;
}

- (void)createFooterView
{
    MJRefreshBackNormalFooter *footerView = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置文字
    [footerView setTitle:@"上拉刷新" forState:MJRefreshStateIdle];
    [footerView setTitle:@"正在加载更多数据" forState:MJRefreshStateRefreshing];
    [footerView setTitle:@"-已经到底了-" forState:MJRefreshStateNoMoreData];
    // 设置字体
    footerView.stateLabel.font = [UIFont systemFontOfSize:13];
    // 设置颜色
    footerView.stateLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1];
    self.tableView.mj_footer = footerView;
}

- (void)loadNewData{
    if (self.isLoading) {
        return;
    }
    self.curPageNum = 1;
    self.refreshType = ETRefreshDown;
    
    [self getAllshareProfit];
    
}

- (void)loadMoreData{
    if (self.isLoading) {
        return;
    }
    self.refreshType = ETRefreshUp;
    self.curPageNum++;
    if ([self.ifHasMore isEqualToString:@"0"]) {
        /*
        [self showSuccessResultTips:@"无更多数据" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF];
         */
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    
    [self getAllshareProfit];
}

-(void)getAllshareProfit
{
     [self.tableView setHidden:NO];
    GetAllProfitRequest *request = [[GetAllProfitRequest alloc] init];
    request.pageNum = [NSString stringWithFormat:@"%ld",(long)self.curPageNum];
    request.pageSize = PAGESIZE;
    request.type = self.typeStr;
    self.isLoading = YES;
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/order/commissionListC0200"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOSTNOTips:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        self.isLoading = NO;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self dealGetAllshareProfit:responseObject];
        }else{
            [self.tableView setHidden:YES];
        }
        
    } FailedHandler:^(NSError *error) {
        
        self.isLoading = NO;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    }];
    
}
-(void)dealGetAllshareProfit:(id)responseObject
{
    GetAllProfitResponse *getAllResponse = [GetAllProfitResponse mj_objectWithKeyValues:responseObject];
    
    if (self.refreshType == ETRefreshUp) {
        
        if (getAllResponse.response.commissionList.count == 0) {
            self.ifHasMore = @"0";
        }
        
        for (GetAllProfitTrade *trade in getAllResponse.response.commissionList) {
            
            
            if (trade.list.count < 10) {
                self.ifHasMore = @"0";
            }else
            {
                self.ifHasMore = @"1";
            }
            
            
            for (GetAllProfitRecord *record in trade.list) {
                NSLog(@"%@",record.payAmount);
                [self.modelArray addObject:record];
                
            }
            
        }
    }else
    {
        [self.modelArray removeAllObjects];
        for (GetAllProfitTrade *trade in getAllResponse.response.commissionList) {
            for (GetAllProfitRecord *record in trade.list) {
                NSLog(@"%@",record.payAmount);
                [self.modelArray addObject:record];
            }
            
        }
    }
    
    
    
    if (self.modelArray.count == 0) {
        self.tableView.hidden = YES;
    }
    
    
    [self.tableView reloadData];
    
}
-(void)GetAmount
{
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/book/incomeInfo"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOSTNOTips:url Parameters:nil HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self dealEarningsDetailResponse:responseObject];
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
}
-(void)clickwithdrawBtnAction
{
    WithdrawViewController *withdrawVC = [[WithdrawViewController alloc] init];
    withdrawVC.ableWithdrawStr = self.ableWithdrawNumLabStr;
    [self.navigationController pushViewController:withdrawVC animated:YES];
}
//点击全部
-(void)totalBtnAction
{
    self.typeStr = @"2";
    
    [self showborderWithBtn:self.sv.totalBtn];
    [self hideborderWithBtn:self.sv.withdrawBtn];
    [self hideborderWithBtn:self.sv.shareProfitBtn];
    
    [self selectbtnAction];
    [self.modelArray removeAllObjects];
    [self.tableView reloadData];
    [self getAllshareProfit];
    
}
//点击分润
-(void)shareProfitBtnAction
{
    
    self.typeStr = @"0";
    [self showborderWithBtn:self.sv.shareProfitBtn];
    [self hideborderWithBtn:self.sv.totalBtn];
    [self hideborderWithBtn:self.sv.withdrawBtn];
    
    
    [self selectbtnAction];
    [self.modelArray removeAllObjects];
    [self.tableView reloadData];
    [self getAllshareProfit];
}
//点击提现
-(void)withdrawBtnAction
{
    self.typeStr = @"1";
    [self showborderWithBtn:self.sv.withdrawBtn];
    [self hideborderWithBtn:self.sv.totalBtn];
    [self hideborderWithBtn:self.sv.shareProfitBtn];
    
    [self selectbtnAction];
    [self.modelArray removeAllObjects];
    [self.tableView reloadData];
    [self getAllshareProfit];
}

-(void)showborderWithBtn:(UIButton *)button
{
    button.layer.borderColor = [UIColor colorWithRed:91 / 255.0 green:113 / 255.0 blue:255 / 255.0 alpha:1].CGColor;
    button.layer.borderWidth = 1;
    [button setTitleColor:[UIColor colorWithRed:91 / 255.0 green:113 / 255.0 blue:255 / 255.0 alpha:1] forState:(UIControlStateNormal)];
    button.selected = YES;
}

-(void)hideborderWithBtn:(UIButton *)button
{
    button.layer.borderWidth = 0;
    [button setTitleColor:[UIColor colorWithRed:51 / 255.0 green:51 / 255.0 blue:51 / 255.0 alpha:1] forState:(UIControlStateNormal)];
    button.selected = NO;
}


-(void)selectbtnAction
{
    
    self.ev.selectbtn.selected = !self.ev.selectbtn.selected;
    if (self.ev.selectbtn.selected) {
        self.ev.selectImv.image = [UIImage imageNamed:@"icon_arrow_purple_up"];
        //更新tableViewFrame并弹出View
        [self addViewAndUpdateFrame];
        
    }else
    {
        //更新tableViewFrame并移除View
        [self removeViewAndUpdateFrame];
        self.ev.selectImv.image = [UIImage imageNamed:@"icon_arrow_down"];
        
    }
}
-(void)removeViewAndUpdateFrame
{
    [self.sv removeFromSuperview];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.ev.lineView.mas_bottom);
        make.bottom.equalTo(self.ev);
    }];

    
    
}

-(void)addViewAndUpdateFrame
{
    self.tableView.hidden = NO;
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.top.equalTo(self.ev.lineView.mas_bottom).offset(55);
            make.bottom.equalTo(self.ev);
        }];

    if (self.sv == nil) {
        self.sv = [[SelectView alloc] init];
    }
    
    [self.ev.bottomView addSubview:self.sv];
    [self.sv mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.ev);
        make.right.equalTo(self.ev);
        make.top.equalTo(self.ev.lineView.mas_bottom).offset(-1);
        make.height.mas_equalTo(55);
    }];
    
    
    
    if (self.sv.totalBtn.selected) {
        [self showborderWithBtn:self.sv.totalBtn];
        [self hideborderWithBtn:self.sv.shareProfitBtn];
        [self hideborderWithBtn:self.sv.withdrawBtn];
    }else if (self.sv.shareProfitBtn.selected)
    {
        [self showborderWithBtn:self.sv.shareProfitBtn];
        [self hideborderWithBtn:self.sv.totalBtn];
        [self hideborderWithBtn:self.sv.withdrawBtn];
    }else if (self.sv.withdrawBtn.selected)
    {
        [self showborderWithBtn:self.sv.withdrawBtn];
        [self hideborderWithBtn:self.sv.totalBtn];
        [self hideborderWithBtn:self.sv.shareProfitBtn];
    }
    
    
    
    [self.sv.totalBtn addTarget:self action:@selector(totalBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.sv.shareProfitBtn addTarget:self action:@selector(shareProfitBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.sv.withdrawBtn addTarget:self action:@selector(withdrawBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}
-(void)createTopView
{
    self.ev = [[EarningsDetailView alloc] initWithFrame:(CGRectMake(15, 15, self.view.frame.size.width - 30, self.view.frame.size.height - 30 - 64))];
    [self.view addSubview:self.ev];
}

-(void)createTableView
{
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.layer.cornerRadius = 5;
    [self.ev.bottomView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.ev.lineView.mas_bottom);
        make.bottom.equalTo(self.ev);
    }];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerClass:[EarnDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EarnDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    GetAllProfitRecord *record = self.modelArray[indexPath.row];
        cell.titleLab.text = record.businessType;
        cell.dateLab.text = record.tradeTime;
        cell.moneyLab.text = record.payAmount;
        //最后一个cell不显示分割线
        if (indexPath.row == self.modelArray.count - 1) {
            cell.lineView.hidden = YES;
        }else
        {
            cell.lineView.hidden = NO;
        }
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.01)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}


@end
